package com.gongxt.data;

import android.content.Context;
import android.database.Cursor;
import android.provider.CallLog.Calls;
import android.util.Log;

public class CallAndSmsHelper {
	private static String TAG = "CallAndSmsHelper";
	
	private static CallAndSmsHelper instance = null;
	private static Context mContext;
		
	private CallAndSmsHelper(Context c){
		mContext = c.getApplicationContext();
	}

	public static CallAndSmsHelper getInstance(Context context){
		if (instance == null){
			instance = new CallAndSmsHelper(context.getApplicationContext());
		}
		
		return instance;
	}
	
	public int checkMissCallNumber(){
		Cursor csr = null;
		int nMissCall = 0;
		
		try{
			csr = mContext.getContentResolver().query(Calls.CONTENT_URI, 
					new String[] { Calls.NUMBER, Calls.TYPE, Calls.NEW }, 
					Calls.TYPE + "=? and " + Calls.NEW + "=1", 
					new String[] { String.valueOf(Calls.MISSED_TYPE) },
					Calls.DEFAULT_SORT_ORDER);
	
			if (csr != null) {
				nMissCall = csr.getCount();
			}
			
			Log.d(TAG, "set miss call number: " + nMissCall);
			
		}catch(Exception ex){
			Log.e(TAG, ex.getMessage());
			
		}finally{
			if (csr != null && !csr.isClosed()){
				csr.close();
			}
		}
		
		return nMissCall;
	}
	
	private int mReceivedSmsThreadID = 0;
	
	public int checkReceivedSmsNumber(){
		Cursor c = null;
		int nReceivedSms = 0;
		
		try{
			c = mContext.getContentResolver().query(SMS.CONTENT_URI, 
					new String[] { SMS.THREAD_ID }, 
					SMS.TYPE + "=? and " + SMS.READ + "<>1", 
					new String[] { String.valueOf(SMS.MESSAGE_TYPE_INBOX) },
					SMS.DATE + " DESC");
	
			if (c != null) {
				nReceivedSms = c.getCount();
				
				// restore last thread ID
				c.moveToFirst();
				if (nReceivedSms != 0){
					mReceivedSmsThreadID = c.getInt(0);
				}
			}
			
			Log.d(TAG, "set miss call number: " + nReceivedSms);
			
		}catch(Exception ex){
			Log.e(TAG, ex.getMessage());
			
		}finally{
			if (c!= null && !c.isClosed()){
				c.close();
			}
		}
		
		return nReceivedSms;
	}
	
	public int getInboxSmsCount(){
		Cursor c = null;
		int nSmsNumber = 0;
		
		try{
			c = mContext.getContentResolver().query(SMS.CONTENT_URI, 
					new String[] { SMS.THREAD_ID }, 
					SMS.TYPE + "=?", 
					new String[] { String.valueOf(SMS.MESSAGE_TYPE_INBOX) },
					SMS.DATE + " DESC");
	
			if (c != null) {
				nSmsNumber = c.getCount();
			}
			
		}catch(Exception ex){
			Log.e(TAG, ex.getMessage());
			
		}finally{
			if (c!= null && !c.isClosed()){
				c.close();
			}
		}
		
		return nSmsNumber;		
	}
	
	public int getLastSmsThreadID(){
		Log.d(TAG, "last SMS thread ID: " + mReceivedSmsThreadID);
		return mReceivedSmsThreadID;
	}
}
